package black.market.main;

import java.util.List;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import dalvik.system.DexClassLoader;

public class CustomClassLoader {
	private Context mContext = null;

	private CustomClassLoader(Context mContext) {
		super();
		this.mContext = mContext;
	}

	public static CustomClassLoader newInstance(Context mContext) {
		return new CustomClassLoader(mContext);

	}

	private static DexClassLoader getDexClassLoader(String dexPath) {
		String dexOutputDir = Environment.getExternalStorageDirectory().getAbsolutePath();
		String libPath = null;
		return new DexClassLoader(dexPath, dexOutputDir, libPath, ClassLoader.getSystemClassLoader().getParent());
	}

	public Context getPackageContext(String packageName) throws NameNotFoundException {
		return mContext.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
	}

	private String getSourceDir(String packageName) {
		String res = null;
		PackageManager pm = mContext.getPackageManager();
		List<PackageInfo> list = pm.getInstalledPackages(PackageManager.GET_META_DATA);
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).packageName.equals(packageName)) {
				res = list.get(i).applicationInfo.sourceDir;
			}
		}
		return res;
	}

	public Class<?> getInstalledAppDexClass(String packageName, String activityName) throws ClassNotFoundException {
		DexClassLoader loader = getDexClassLoader(getSourceDir(packageName));
		return loader.loadClass(packageName + "." + activityName);
	}
}
